package com.yvan.leto.server.utils;

import com.google.common.base.Splitter;
import com.google.common.base.VerifyException;
import com.yvan.platform.StringUtils;

import java.util.List;
import java.util.regex.Pattern;

public class VerifyHelper {

    private final static Pattern PROJECT_NAME_VERIFY = Pattern.compile("^[a-zA-Z0-9\\-_]{3,128}$");
    private final static Pattern CONFIG_FILE_NAME_VERIFY = Pattern.compile("^[a-zA-Z0-9_@\\!\\#\\$\\^\\(\\)\\~]{1,100}\\.[a-zA-Z0-9]{1,28}$");
    private final static Pattern CONFIG_PATH_NAME = Pattern.compile("^[a-zA-Z0-9\\-_\\.@\\!\\#\\$\\^\\(\\)\\~]{1,128}$");

    public static String projectName(String projectName) {
        if (StringUtils.isBlank(projectName)) {
            return "project name not allow null";
        }
        if (!PROJECT_NAME_VERIFY.matcher(projectName).matches()) {
            return "project name only allow charactor:[a-z,A-Z,0-9,-,_], min-length:3, max-length:128";
        }
        return "";
    }

    public static void main(String[] args) {
        //System.out.println(projectName("abc123ABC"));
        System.out.println(projectName("abc 123ABC"));
    }

    public static String configFilePath(String pathRaw) {
        if (StringUtils.isBlank(pathRaw)) {
            throw new VerifyException("path name not allow null");
        }

        final String path = FileUtils.normalizePath(pathRaw);
        final List<String> paths = Splitter.on("/").splitToList(path);
        if (paths.size() < 1 || paths.size() > 7) {
            throw new VerifyException("paths deep < 7");
        }
        for (int i = 0; i < paths.size() - 1; i++) {
            if (!CONFIG_PATH_NAME.matcher(paths.get(i)).matches()) {
                throw new VerifyException("folder name only allow charactor:[a-z,A-Z,0-9,-_.@!#$^()~], min-length:1, max-length:128");
            }
        }
        final String fileName = paths.get(paths.size() - 1);
        if (!CONFIG_FILE_NAME_VERIFY.matcher(fileName).matches()) {
            throw new VerifyException("file name only allow charactor:[a-z,A-Z,0-9,_@!#$^()~]{1,100}.[a-zA-Z0-9]{1,28}\nfor example: global.yaml, global(1).properties");
        }

        return path;
    }
}
